package com.newbingo.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.StringUtils;

import com.newbingo.dao.imple.IPeriodGameDao;
import com.newbingo.entity.Game;
import com.newbingo.entity.PeriodGame;
import com.newbingo.util.Pager;

public class PeriodGameDao extends HibernateDaoSupport implements
		IPeriodGameDao {
	private static final Log log = LogFactory.getLog(PeriodGameDao.class);

	public void attachDirty(PeriodGame instance) {
		log.debug("attaching PeriodGame instance");
		try {
			getSession().saveOrUpdate(instance);
			instance=new PeriodGame();
			log.debug("attach PeriodGame successful");
		} catch (RuntimeException re) {
			log.error("attach PeriodGame failed", re);
			throw re;
		}

	}

	/**
	 * 删除
	 * 
	 */
	public void delete(PeriodGame persistentInstance) {
		log.debug("deleting PeriodGame instance");
		try {
			PeriodGame periodGame=findById(persistentInstance.getPgno());
			getSession().delete(periodGame);
			log.debug("delete PeriodGame susscessful");
		} catch (RuntimeException re) {
			log.error("delete PeriodGame failed", re);
			throw re;
		}

	}

	/**
	 * 查询所有
	 */
	public List findAll() {
		log.debug("finding all PeriodGame instance");
		try {
			String queryString = "from PeriodGame";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List findByExample(PeriodGame instance) {
		log.debug("finding PeriodGame instance by example");
		try {
			List results = getSession().createCriteria(
					"com.newbingo.entity.PeriodGame").add(
					Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/**
	 * 根据GameTable编号gtno查询
	 * 
	 * @return pager
	 */
	public Pager findByGtNO(int start, int limit, int gtno) {
		Pager pager = new Pager();
		Criteria cri = this.getSession().createCriteria(PeriodGame.class);
		cri.add(Expression.eq("gameTable", gtno));
		cri.setProjection(Projections.rowCount());
		cri.setResultTransformer(Criteria.ROOT_ENTITY);
		cri.setFirstResult(start);
		cri.setMaxResults(limit);
		List list = cri.list();
		pager.setData(list);
		return null;
	}

	/**
	 * 根据Id查询
	 * 
	 * @return PeriodGame
	 */
	public PeriodGame findById(Integer id) {
		log.debug("getting PeriodGame instance with id: " + id);
		try {
			PeriodGame instance = (PeriodGame) getSession().get(
					"com.newbingo.entity.PeriodGame", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/**
	 * 分页查询
	 * 
	 * @return Pager
	 */
	public Pager findByPage(int start, int limit, Object type) {
		Pager pager = new Pager();
		Criteria cri = getSession().createCriteria(PeriodGame.class);
		// 判断是否有查询条件
		if (type != null) {
			cri.add(Expression.eq("type", type));
		}
		cri.setProjection(Projections.rowCount());
		pager.setTotalSize(((Number) cri.uniqueResult()).intValue());
		cri.setProjection(null);
		cri.setResultTransformer(Criteria.ROOT_ENTITY);
		cri.setFirstResult(start);
		cri.setMaxResults(limit);
		List list = cri.list();
		pager.setData(list);
		return pager;
	}
	
	/**
	 * 查询游戏历史开奖记录
	 * @param gtno 游戏桌编号
	 * @param date 时间
	 * @return Pager
	 * */
    public Pager findHistoryRecord(int start,int limit,int gtno,String date){
    	Pager pager=new Pager();
    	Criteria cri=getSession().createCriteria(PeriodGame.class);
    	cri.createAlias("gameTable", "gt");
    	cri.add(Expression.eq("gt.gtno", gtno));
    	if (date!=null && StringUtils.hasText(date)) {
			cri.add(Expression.like("periodTime", date, MatchMode.ANYWHERE));
		}
    	cri.add(Expression.eq("isDraw",1));
		cri.setProjection(Projections.rowCount());
		pager.setTotalSize(((Number) cri.uniqueResult()).intValue());
		cri.setProjection(null);
		cri.setResultTransformer(Criteria.ROOT_ENTITY);
		cri.setFirstResult(start);
		cri.setMaxResults(limit);
		List list = cri.list();
		System.out.println("查询出来的list的大小："+list.size());
		pager.setData(list);
		return pager;
    }
	/**
	 * 根据PeriodNum查询
	 * 
	 * @return list
	 */
	public List findByPeriodNum(Object periodNum) {
		// TODO Auto-generated method stub
		return findByProperty(PERIODNUM, periodNum);
	}

	/**
	 * 根据PeriodTime查询
	 * 
	 * @return list
	 */
	public List findByPeriodTime(Object periodTime) {
		// TODO Auto-generated method stub
		return findByProperty(PERIODTIME, periodTime);
	}
	
	/**
	 * 根据游戏桌编号获取最新一期的游戏
	 * @return
	 */
	public PeriodGame getCurrentPeriodGame(int gtno){
		log.debug("getting the lastest PeriodGame instance" );
		try {
			Criteria cri=getSession().createCriteria(PeriodGame.class);
			cri.createAlias("gameTable", "gt");
			cri.add(Expression.eq("gt.gtno", gtno));
			//倒序排列，从而根据游戏桌获取最近一条的彩票期数
			cri.addOrder(Order.desc("pgno"));
			cri.setFirstResult(0);
			cri.setMaxResults(1);
			List results=cri.list();
			if(results!=null &&results.size()>0){
				return (PeriodGame)results.get(0);
			}
			return null;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/**
	 * 根据属性查询
	 */
	public List findByProperty(String propertyName, Object value) {
		log.debug("finding PeriodGame instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from PeriodGame as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/**
	 * 修改
	 */
	public PeriodGame merge(PeriodGame detachedInstance) {
		log.debug("merging PeriodGame Instance");
		try {
			PeriodGame result = (PeriodGame) getSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/**
	 * 保存
	 */
	public void save(PeriodGame transientInstance) {
		log.debug("saving PeriodGame instance");
		try {
			getSession().save(transientInstance);
			log.debug("sava successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

}
